﻿// ===============================================================================
// Copyright (c) 2007-2020 西安交通信息投资营运有限公司 版权所有
// 作者:张谦
// ===============================================================================

using DevExpress.XtraEditors.Controls;
using System;
using System.Threading.Tasks;
using XCI.Core;
using XCI.Extensions;
using XCI.Sys.Filter;
using XCI.Sys.Model;
using XCI.Sys.Service;
using XCI.Windows;
using XCI.Helper;

namespace XCI.Sys.Forms
{
    /// <summary>
    /// 系统用户管理
    /// </summary>
    [FormCaption("系统用户管理")]
    public partial class FrmUserManager : BaseForm
    {
        private readonly bool allowSelect = SysApp.Permit("sys.user.select");
        private readonly bool allowInsert = SysApp.Permit("sys.user.insert");
        private readonly bool allowUpdate = SysApp.Permit("sys.user.update");
        private readonly bool allowDelete = SysApp.Permit("sys.user.delete");
        private readonly bool allowExport = SysApp.Permit("sys.user.export");
        private readonly bool allowRevisePassword = SysApp.Permit("sys.user.revisePassword");

        public FrmUserManager()
        {
            InitializeComponent();
            gridControl.ModelType = typeof(SysUser);
        }

        /// <summary>
        /// 加载首页数据
        /// </summary>
        private Task LoadFirstPageAsync()
        {
            return Mutex.EndAsync(() => gridControl.LoadFirstPageAsync());
        }

        /// <summary>
        /// 显示数据编辑
        /// </summary>
        /// <param name="param">数据编辑参数</param>
        private void ShowEditForm(EditFormArgs param)
        {
            var editForm = new FrmUserEdit(param);
            editForm.ShowDialogOk(async () => await gridControl.LoadAsync());
        }

        /// <summary>
        /// 页面加载事件
        /// </summary>
        private async void FrmUserManager_Load(object sender, EventArgs e)
        {
            Mutex.Begin(() =>
            {
                filterStatus.SelectedIndex = 0;
                filterCategory.SelectedIndex = 0;
            });
            await filterLayoutControl.BindingDataAsync();
            await LoadFirstPageAsync();
        }

        /// <summary>
        /// 新建事件
        /// </summary>
        private void BtnNew_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            ShowEditForm(EditFormArgs.Create());
        }

        /// <summary>
        /// 修改事件
        /// </summary>
        private void BtnEdit_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            ShowEditForm(EditFormArgs.Edit(gridControl.SelectedId));
        }

        /// <summary>
        /// 复制事件
        /// </summary>
        private async void BtnCopy_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (MessageBoxHelper.ShowWarnYesNo("确定要复制选中的数据吗?") != System.Windows.Forms.DialogResult.Yes) return;
            await SysUserService.Instance.CopyAsync(gridControl.SelectedId);
            await gridControl.LoadAsync();
        }

        /// <summary>
        /// 删除事件
        /// </summary>
        private async void BtnDelete_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            await gridControl.DeleteAsync();
        }

        /// <summary>
        /// 导出事件
        /// </summary>
        private async void BtnExport_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            var filter = gridControl.GetFilter();
            await App.Excel.ExportFileDialogAsync((path, fields) => SysUserService.Instance.ExportAsync(path, filter as SysUserFilter), "系统用户列表", this);
        }

        /// <summary>
        /// 重置密码
        /// </summary>
        private void BtnRevisePassword_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            new FrmRevisePassword(gridControl.SelectedIds).ShowDialogOk();
        }

        /// <summary>
        /// 刷新按钮
        /// </summary>
        private async void BtnRefreshCache_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            await SysUserService.Instance.RefreshCacheAsync();
            await gridControl.LoadAsync();
            MessageBoxHelper.ShowMessage("缓存刷新成功");
        }

        /// <summary>
        /// 属性按钮
        /// </summary>
        private void BtnProperty_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            gridControl.InvokeRowDoubleClick();
        }

        private async void RepositoryEditStatus_CheckedChanged(object sender, EventArgs e)
        {
            var edit = gridView.ActiveEditor;
            var col = gridView.FocusedColumn;
            if (col.FieldName.Equals(nameof(SysUser.Status)))
            {
                await SysUserService.Instance.UpdateStatusAsync(gridControl.SelectedId, edit.EditValue.ToBool());
            }
        }

        private void GridControl_LoadData(object sender, LoadDataEventArgs e)
        {
            e.Task = async () => await SysUserService.Instance.SelectPageListAsync(e.Filter as SysUserFilter);
        }

        private void GridControl_DetectFilter(object sender, DetectFilterEventArgs e)
        {
            e.Filter = App.ContainerData.GetModel(layoutGroupFilter, new SysUserFilter());
        }

        private void GridControl_DeleteData(object sender, DeleteDataEventArgs e)
        {
            e.Task = () => SysUserService.Instance.DeleteAsync(gridControl.SelectedIds);
        }

        private void GridControl_RowDoubleClick(object sender, EventArgs e)
        {
            new FrmUserDetails(gridControl).ShowDialogOk();
        }

        private void GridControl_RowSelectionChanged(object sender, EventArgs e)
        {
            btnNew.Enabled = allowInsert;
            btnEdit.Enabled = gridControl.HasSingleSelected && allowUpdate;
            btnCopy.Enabled = gridControl.HasSingleSelected && allowInsert;
            btnDelete.Enabled = gridControl.HasSelected && allowDelete;
            BtnExport.Enabled = gridControl.HasData && allowExport;
            btnRefreshCache.Enabled = allowSelect;
            btnSearch.Enabled = allowSelect;

            BtnProperty.Enabled = gridControl.HasSingleSelected;
            BtnRevisePassword.Enabled = gridControl.HasSelected && allowRevisePassword;
        }

        /// <summary>
        /// 关键字文本框键盘事件
        /// </summary>
        private async void EditName_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
        {
            if (e.KeyChar == R.EnterKey) await LoadFirstPageAsync();
        }

        /// <summary>
        /// 状态发生变化事件
        /// </summary>
        private async void StatusCombo_SelectedIndexChanged(object sender, EventArgs e)
        {
            await LoadFirstPageAsync();
        }

        /// <summary>
        /// 账号类型发生变化事件
        /// </summary>
        private async void CategoryComboBoxEdit_SelectedIndexChanged(object sender, EventArgs e)
        {
            await LoadFirstPageAsync();
        }

        /// <summary>
        /// 机构发生变化事件
        /// </summary>
        private async void EditDepartment_EditValueChanged(object sender, EventArgs e)
        {
            editDeptId.Properties.Buttons[1].Visible = editDeptId.EditValue != null;
            await LoadFirstPageAsync();
        }

        private void EditDepartment_ButtonClick(object sender, ButtonPressedEventArgs e)
        {
            if (e.Button.Index == 1) editDeptId.EditValue = null;
        }

        /// <summary>
        /// 搜索按钮点击事件
        /// </summary>
        private async void BtnSearch_Click(object sender, EventArgs e)
        {
            await LoadFirstPageAsync();
        }

        /// <summary>
        /// 重置按钮点击事件
        /// </summary>
        private async void BtnReset_Click(object sender, EventArgs e)
        {
            Mutex.Begin(() => App.ContainerData.SetModel(layoutGroupFilter, SysUserFilter.Default));
            await LoadFirstPageAsync();
        }

    }
}